<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type {
  VxeGridListeners,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { PermissionApi } from '#/api/types';

import { h, onMounted, ref } from 'vue';

import { Page } from '@vben/common-ui';

import { Button, Modal } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  getPermissionModuleApi,
  getPermissionsApi,
  updatePermissionStatusApi,
} from '#/api/core/modules/permission';
import { $t } from '#/locales';

import EditForm from './modules/edit-form.vue';

const permissionModules = ref<{ label: string; value: string }[]>([]);
onMounted(async () => {
  const { data } = await getPermissionModuleApi();
  permissionModules.value = data.map((item) => {
    return {
      label: item.label,
      value: item.value,
    };
  });
});

// 编辑权限抽屉引用
const editFormRef = ref();

// 存储选中的行数据
const selectedRows = ref<PermissionApi.PermissionVO[]>([]);

// 表格事件监听
const gridEvents: VxeGridListeners<PermissionApi.PermissionVO> = {
  checkboxAll: onSelectionChange,
  checkboxChange: onSelectionChange,
};

// 表格组件
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    collapsed: true,
    submitOnChange: true,
    schema: [
      {
        component: 'Input',
        fieldName: 'name',
        label: $t('system.permission.name'),
        componentProps: {
          placeholder: $t('common.inputText', [$t('system.permission.name')]),
        },
      },
      {
        component: 'Input',
        fieldName: 'code',
        label: $t('system.permission.code'),
        componentProps: {
          placeholder: $t('common.inputText', [$t('system.permission.code')]),
        },
      },
      {
        component: 'ApiSelect',
        fieldName: 'parentId',
        label: $t('system.permission.category'),
        componentProps: {
          allowClear: true,
          placeholder: $t('common.select', [$t('system.permission.category')]),
          api: getPermissionModuleApi,
          afterFetch: (res: any) => {
            const options = [{ label: '根目录', value: '0' }];
            res.data.forEach((item: PermissionApi.PermissionModuleVO) => {
              options.push({
                label: item.label,
                value: item.value,
              });
            });
            return options;
          },
        },
      },
      {
        component: 'Select',
        fieldName: 'status',
        label: $t('common.status'),
        componentProps: {
          allowClear: true,
          placeholder: $t('common.select', [$t('common.status')]),
          options: [
            { label: $t('common.enabled'), value: 1 },
            { label: $t('common.disabled'), value: 0 },
          ],
        },
      },
    ],
  },
  gridEvents,
  gridOptions: {
    columns: [
      {
        type: 'checkbox',
        width: 40,
      },
      {
        field: 'id',
        title: 'ID',
        width: 80,
      },
      {
        field: 'name',
        title: $t('system.permission.name'),
        minWidth: 120,
      },
      {
        field: 'code',
        title: $t('system.permission.code'),
        minWidth: 150,
      },
      {
        field: 'parentId',
        title: $t('system.permission.category'),
        minWidth: 150,
        slots: {
          default: ({ row }) => {
            if (row.parentId === '0') {
              return '根目录';
            }

            const matchedOption = permissionModules.value.find(
              (opt) => opt.value === row.parentId,
            );
            return matchedOption?.label || row.parentId;
          },
        },
      },
      {
        field: 'description',
        title: $t('system.permission.description'),
        minWidth: 150,
      },
      {
        field: 'status',
        title: $t('common.status'),
        width: 100,
        cellRender: {
          attrs: { beforeChange: onStatusChange },
          name: 'CellSwitch',
        },
      },
      {
        field: 'createdTime',
        title: $t('common.createdTime'),
        width: 180,
      },
      {
        align: 'center',
        slots: {
          default: ({ row }) => {
            return [
              h(
                Button,
                {
                  type: 'link',
                  onClick: () => onActionClick({ code: 'edit', row }),
                },
                () => $t('common.edit'),
              ),
            ];
          },
        },
        field: 'operation',
        fixed: 'right',
        title: $t('common.action'),
        width: 160,
      },
    ],
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          const result = await getPermissionsApi({
            current: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
          return {
            records: result.data.records,
            total: result.data.total,
            pageSize: result.data.pageSize,
            currentPage: result.data.current,
          };
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      search: true,
      zoom: true,
    },
    checkboxConfig: {
      checkField: 'checked',
      checkStrictly: false,
      highlight: true,
    },
  } as VxeTableGridOptions<PermissionApi.PermissionVO>,
});

// 监听选择变化事件
function onSelectionChange(params: {
  checked: boolean;
  records: PermissionApi.PermissionVO[];
}) {
  const rows = params.records;
  selectedRows.value = rows || [];
}

// 操作按钮点击处理
function onActionClick(e: { code: string; row: PermissionApi.PermissionVO }) {
  switch (e.code) {
    case 'edit': {
      onEdit(e.row);
      break;
    }
  }
}

// 确认弹窗
function confirm(content: string, title: string) {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      content,
      onCancel() {
        reject(new Error('已取消'));
      },
      onOk() {
        resolve(true);
      },
      title,
    });
  });
}

// 处理状态切换
async function onStatusChange(
  newStatus: number,
  row: PermissionApi.PermissionVO,
) {
  const status: Recordable<string> = {
    0: $t('common.disabled'),
    1: $t('common.enabled'),
  };
  try {
    await confirm(
      $t('ui.confirmMessage.changeStatus', [
        row.name,
        status[newStatus.toString()],
      ]),
      $t('ui.actionTitle.changeStatus'),
    );
    await updatePermissionStatusApi({
      permissionId: row.id,
      status: newStatus,
    });
    return true;
  } catch {
    return false;
  }
}

// 编辑权限
function onEdit(row: PermissionApi.PermissionVO) {
  // 调用编辑表单抽屉的API打开并传递数据
  editFormRef.value.drawerApi.setData(row).open();
}

// 刷新表格
function onRefresh() {
  // 刷新时清空选中状态
  selectedRows.value = [];
  // 调用表格刷新
  gridApi.query();
}
</script>

<template>
  <Page auto-content-height>
    <template #header>
      <div class="flex items-center justify-between">
        <div>{{ $t('system.permission.title') }}</div>
      </div>
    </template>

    <Grid />

    <EditForm ref="editFormRef" @success="onRefresh" />
  </Page>
</template>
